package com.ws.wsdemo;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/test_path/websocket/{userId}/{channel}")
@Component
public class WebSocketServer {
    private Long userId;
    // 静态变量保存SessionMap
    private final static ConcurrentHashMap<Long, Session> sessions = new ConcurrentHashMap<>();

    @Autowired testController testController;


    private static testController testController2;
    @Autowired
    public void setMyService(testController controller) {
        WebSocketServer.testController2 = controller; // 静态变量中转
    }

    @OnOpen
    public void onOpen(Session session,
                       @PathParam("userId") Long userId,
                       @PathParam("channel") String channel){
        System.out.println(testController);
        System.out.println(testController2);
        this.userId = userId;
        System.out.println("连接已经建立: id="+userId+" channel="+channel);
        addSession(userId,session);
    }

    @OnClose
    public void onClose(Session session){
        System.out.println("连接关闭了: id="+ userId);
        removeSession(userId);
    }

    @OnMessage
    public void onMessage(String message,Session session){
        System.out.println(message);
        try {
            session.getBasicRemote().sendText("你传来的消息是"+message);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 添加Session
    public void addSession(Long userId, Session session) {
        sessions.put(userId, session);
    }

    // 移除Session
    public static void removeSession(Long userId) {
        sessions.remove(userId);
    }

    // 获取Session
    public static Session getSession(Long userId) {
        return sessions.get(userId);
    }

    // 向指定用户发送消息
    public static void sendMessageToUser(Long userId, String message) throws IOException {
        Session session = sessions.get(userId);
        if (session != null && session.isOpen()) {
            session.getBasicRemote().sendText(message);
        }
    }

    // 广播消息给所有用户
    public static void broadcast(String message) {
        sessions.forEach((id, session) -> {
            try {
                if (session.isOpen()) {
                    session.getBasicRemote().sendText(message);
                }
            } catch (IOException e) {
                removeSession(id); // 发送失败时移除失效session
            }
        });
    }
}
